﻿namespace PAR
{
    using System;
    using System.IO;
    using System.IO.IsolatedStorage;
    using System.Windows.Controls;
    using Coding4Fun.Phone.Site.Controls;
    using Microsoft.Phone.Controls;
    using Microsoft.Xna.Framework.Audio;

    public partial class MainPage : PhoneApplicationPage
    {      
        public MainPage()
        {
            InitializeComponent();
        }

        private void About_Click(object sender, EventArgs e)
        {
            var about = new Coding4FunAboutPrompt();
            about.Show("RudiGrobler", "rudigrobler", "rudi@bbd.co.za", "http://www.rudigrobler.net");
        }

        private void Record_Click(object sender, EventArgs e)
        {
            string mode = ((ListPickerItem)visualizationModeListPicker.SelectedItem).Content.ToString();

            NavigationService.Navigate(new Uri("/Audio/Recorder.xaml?mode=" + mode, UriKind.Relative));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
            filesListBox.ItemsSource = file.GetFileNames("*.wav");


        }

        private void PlayFromIS(string filename)
        {
            Stream stream = new IsolatedStorageFileStream(filename, FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication());
            var buffer = new byte[stream.Length];
            stream.Read(buffer, 0, (int)stream.Length);

            int sampleRate = Microphone.Default.SampleRate;
            var se = new SoundEffect(buffer, sampleRate, AudioChannels.Mono);
            SoundEffect.MasterVolume = 0.7f;
            se.Play();
        }

        private void filesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string filename = (string)e.AddedItems[0];
            PlayFromIS(filename);
        }
    }
}